// mircoApp/ai-create/VoiceClon/index.js
let app = getApp();
const skinBehavior = require('../../../utils/themeSkin/skinBehavior');
Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    imgPath: app.globalData.imgPath,
    showAgreement: false,
    showTransition: true,
    noteShow: false,
    sex: null,
    voice_name: null,
    recorderManager: null,

    activeRecordeIndex: 0,
    activeRecordeDomo: null,
    activeRecordeStauts: 0,
    activeRecordeText: '请朗读',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getData();
  },
  async getData(){
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.audio-clone.get-agreement');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        business_id: this.options.business_id || 0
      }
    });
    let { result, msg, data } = response.data;
    if(!result) return app.tips(msg);
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: this.data.themeBaseColor
    });
    this.setData({
      body_clone_agreement: data,
      showAgreement: true
    });
  },
  toNextPage(){
    wx.redirectTo({
      url: `/mircoApp/ai-create/SpaceDetails/index?business_id=${this.options.business_id || 0}&tab=2`
    });
    // wx.navigateBack({
    //   delta: 1,
    //   fail: ()=>{
    //     wx.redirectTo({
    //       url: `/mircoApp/ai-create/SpaceDetails/index?business_id=${this.options.business_id || 0}&tab=1`
    //     })
    //   }
    // })
  },
  onClickVal(e) {
    let {
      name,
      val
    } = e.currentTarget.dataset;
    this.setData({
      [name]: val
    });

    if(name == 'showAgreement') {
      this.checkRecorderScope();
    }
  },
  checkRecorderScope(){
    wx.getSetting({
      success:(res)=> {
        if (!res.authSetting['scope.record']) {
          // 用户未授权，需要请求权限
          wx.authorize({
            scope: 'scope.record',
            success:()=> {
              // 用户同意授权，可以进行录音操作
              this.toRecorderManager();
            },
            fail:()=> {
              // 用户拒绝授权，需要引导用户手动开启权限
              wx.showModal({
                title: '提示',
                content: '您未授权录音功能，是否前往设置？',
                success:(res)=> {
                  if (res.confirm) {
                    wx.openSetting({
                      success:(settingData)=> {
                        if (settingData.authSetting['scope.record']) {
                          this.toRecorderManager();
                          console.log('用户已授权录音功能');
                        } else {
                          console.log('用户未授权录音功能');
                        }
                      }
                    });
                  }
                }
              });
            }
          });
        } else {
          // 用户已授权，可以进行录音操作
          this.toRecorderManager();
        }
      }
    });
  },
  RecorderMag(){
    this.getAudioData();
    this.checkRecorderScope();
    // this.toRecorderManager();
  },
  toRecorderManager(){
    this.data.recorderManager = wx.getRecorderManager();
    this.data.recorderManager.onStart(() => {
      console.log('recorder start')
    })
    this.data.recorderManager.onPause(() => {
      console.log('recorder pause')
    })
    this.data.recorderManager.onStop((res) => {
      console.log('recorder stop', res)
      const { tempFilePath } = res;
      this.tempFilePath = tempFilePath;
      this.upVoice();
      // this.InspectionREC();
    })
    this.data.recorderManager.onFrameRecorded((res) => {
      // const { frameBuffer } = res
      // console.log('frameBuffer.byteLength', frameBuffer.byteLength)
    })
  },
  async getAudioData(){
    if(!this.data.voice_name) {
      app.tips('请设置声音名称','error');
      return;
    }
    if(!this.data.sex) {
      app.tips('请选择声音性别','error');
      return;
    }
    if(!this.innerAudioContext) {
      this.innerAudioContext = wx.createInnerAudioContext({
        useWebAudioImplement: true 
      });
    }
    
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.audio-clone');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        sex: this.data.sex,
        business_id: this.options.business_id || 0,
        voice_name: this.data.voice_name
      }
    });
    let { result, msg, data } = response.data;
    if(!result) return app.tips(msg);


    // data.demo_list.splice(1,17)


    this.setData(data);
    this.setData({
      noteShow: true,
      activeRecordeDomo: data.demo_list[0]
    });
    this.innerAudioContext.src = data.demo_list[0].demo_audio;
  },
  playDomo(){
    if(this.data.activeRecordeStauts == 0) {
      this.innerAudioContext.play() // 播放
    }
  },
  onStartREC(){
    console.log('开始录音')
    app.tips('开始录音');
    this.setData({
      activeRecordeStauts: 1 //开始录音
    });
    this.data.recorderManager.start({
      sampleRate: 48000, // 采样率
      numberOfChannels: 1, // 单声道
      encodeBitRate: 192000, // 编码码率
      format: 'wav', // 音频格式
    });
  },
  onStopREC(){
    console.log('结束录音',this.data.recorderManager);
    app.tips('录音检验中');
    this.setData({
      activeRecordeStauts: 2 //校验中
    });
    this.data.recorderManager.stop();
  },
  onChangeSex(event) {
    this.setData({
      sex: event.detail,
    });
  },

  upVoice(){
    wx.showLoading({
      title: '录音校验中',
    })
    let wx_token = wx.getStorageSync('wx_token');
    let urlStr = app.getNetAddresss('upload.uploadPic');
    urlStr += "&upload_type=audio";
    console.log('tempFilePath',this.tempFilePath)
    const uploadTask = wx.uploadFile({
      url: urlStr, //仅为示例，非真实的接口地址
      filePath: this.tempFilePath,
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data",
        Cookie: "PHPSESSID=" + wx_token,
      },
      formData: {
        // 和服务器约定的token, 一般也可以放在header中
        '_wx_token': wx.getStorageSync('wx_token')
      },
      success:(res)=>{
        let data = JSON.parse(res.data);
        console.log('success',data)
        if (data.result == 1) {
          this.path = data.data.img;
          this.InspectionREC();
        } else {
          wx.hideLoading()
          app.tips(data.msg);
          this.setData({
            activeRecordeStauts: 0 //录音重置
          });
        }
      },complete: (e) => {
        console.log('complete',e)
      },
      fail:(err)=>{
        console.log('fail',err)
        wx.hideLoading()
        app.tips("上传失败",'error');
        this.setData({
          activeRecordeStauts: 0 //录音重置
        });
      }
    });
  },
  async InspectionREC(){
    console.log('InspectionREC 参数==========',this.data.voice_id,this.data.demo_list[0])
    console.log('InspectionREC 参数==========',this.data.demo_list[this.data.activeRecordeIndex].audio_id)
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.audio-clone.read');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        voice_id: this.data.voice_id,
        audio_id: this.data.demo_list[this.data.activeRecordeIndex].audio_id,
        path: this.path,
        business_id: this.options.business_id || 0
      }
    });
    this.setData({
      activeRecordeStauts: 0 //录音重置
    });
    let { result, msg, data } = response.data;
    console.log('InspectionREC===========',response)
    if(!result) {
      wx.hideLoading();
      return app.tips(msg);
    }
   
    if(this.data.activeRecordeIndex ==  this.data.demo_list.length - 1){
      console.log('录音全部校验完成===========')
      wx.hideLoading();
      this.setData({
        activeRecordeStauts: 3 //录音全部校验完成
      });
      this.innerAudioContext.destroy(); // 释放音频资源
      return;
    }
    this.setData({
      showTransition: false
    });
    setTimeout(() => {
      wx.hideLoading()
      this.setData({
        activeRecordeIndex: this.data.activeRecordeIndex + 1,
        activeRecordeDomo: this.data.demo_list[this.data.activeRecordeIndex + 1],
        showTransition: true
      });
      this.innerAudioContext.src = this.data.activeRecordeDomo.demo_audio;
    }, 500);
  },
  async subCloneAd(){
    if(this.data.activeRecordeStauts != 3) {
      app.tips('请先录制音频','error');
      return;
    }
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.audio-clone.create');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        voice_id: this.data.voice_id,
        name: this.data.voice_name,
        sex: this.data.sex,
        business_id: this.options.business_id || 0
      }
    });
    let { result, msg, data } = response.data;
    app.tips(msg);
    if (!result) return;
    this.toNextPage();
  },
  resetREC(){
    wx.showModal({
      title: '提示',
      content: '重新录制需从第一条进行录制，请确认是否重新录制！',
      success (res) {
        if (res.confirm) {
          this.setData({
            activeRecordeStauts: 0,
            activeRecordeIndex: 0,
            demo_list: []
          });
          this.getAudioData();
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if(this.innerAudioContext){
      this.innerAudioContext.destroy(); // 释放音频资源
      this.innerAudioContext = null;
    } 
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      path: '/mircoApp/ai-create/SpacePortal/index',
    };
  }
})